package com.buyOnline.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

import com.buyOnline.DbcpPoolPackage.DbcpPool;
import com.buyOnline.DbcpPoolPackage.needToClose;
import com.buyOnline.dao.IProductDao;
import com.buyOnline.entity.Product;

public class productDaoImpl implements IProductDao{

	public List<Product> findAll() {
		// TODO Auto-generated method stub
		String sql="SELECT * FROM t_product ORDER BY id";
		List<Product> productList=new ArrayList<Product>();
		Connection conn = null;
		try {
			conn = DbcpPool.getConnection();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		needToClose newNeedtoClose=DbcpPool.executeQuery(conn,sql);
		ResultSet rs=newNeedtoClose.getRs();
		
		try
		{
			while(rs.next())
			{
				Product productOption=new Product();
				productOption.setName(rs.getString("name"));
				productOption.setDescription(rs.getString("description"));
				productOption.setPrice(rs.getInt("price"));
				productOption.setStock(rs.getInt("stock"));
				productList.add(productOption);
			}
		}
		catch(SQLException e)
		{
			e.printStackTrace();
		}
		
		DbcpPool.closeAll(newNeedtoClose);
		return productList;
	}

	public int initialize(String name, String description, int price, int stock, String proPic) {
		// TODO Auto-generated method stub
		String sql="INSERT INTO t_product (name,description,price,stock,proPic) VALUES (?,?,?,?,?)";
		Connection conn=null;
		try {
			conn=DbcpPool.getConnection();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		int result=0;
		PreparedStatement ps=DbcpPool.executePreparedStatementReturnPS(conn, sql);
		try
		{
			ps.setString(1, name);
			ps.setString(2, description);
			ps.setInt(3, price);
			ps.setInt(4, stock);
			ps.setString(5, proPic);
			result=ps.executeUpdate();
		}
		catch(SQLException e)
		{
			e.printStackTrace();
		}
		
		needToClose newNeedtoClose=new needToClose();
		newNeedtoClose.setAll(conn, ps, null);
		
		DbcpPool.closeAll(newNeedtoClose);
		return result;
	}


}
